const { createStoreBindings } = require('mobx-miniprogram-bindings');
const dateHelper = require('../../../../store/helpers/date_helper');
const { projectStore } = require('../../store/project_store');
const { computed } = require('mobx-miniprogram');

Component({
  options: {
    addGlobalClass: true
  },

  data: {
    isLoading: false,
    list: [],
    currentProject: null,
    
    // 日期相关
    now: Date.now(),
    selectedDate: Date.now()
  },

  observers: {
    // 使用observers监听选择日期变化
    'selectedDate': function(date) {
      this._updateDateComputed(date);
    }
  },

  lifetimes: {
    attached() {
      // 创建MobX Store绑定
      this.storeBindings = createStoreBindings(this, {
        store: projectStore,
        fields: [
          'projectList',
          'currentProject',
          'recentProjects',
          'upcomingDeadlineProjects'
        ],
        actions: [
          'loadList',
          'loadProjectDetail'
        ]
      });
      
      // 创建计算属性
      this.computedFields = computed({
        // 项目创建时间的友好显示
        projectTimes: () => {
          return this.data.recentProjects.map(project => ({
            ...project,
            createTimeAgo: dateHelper.timeAgo(project.ADD_TIME),
            deadlineFormatted: dateHelper.formatDate(project.PROJECT_DEADLINE),
            deadlineStatus: this._getDeadlineStatus(project.PROJECT_DEADLINE)
          }));
        },
        
        // 当前日期格式化
        formattedDate: () => {
          return dateHelper.format(this.data.selectedDate, 'YYYY-MM-DD');
        },
        
        // 当前日期中文格式化
        formattedDateCN: () => {
          return dateHelper.formatCN(this.data.selectedDate);
        },
        
        // 日期相对时间
        dateTimeAgo: () => {
          return dateHelper.timeAgo(this.data.selectedDate);
        },
        
        // 是否选择了未来日期
        isFutureDate: () => {
          return dateHelper.isAfter(this.data.selectedDate, this.data.now);
        },
        
        // 选择日期与今天的天数差
        dayDifference: () => {
          return dateHelper.diff(this.data.selectedDate, this.data.now, 'day');
        },
        
        // 当前项目的截止日期状态
        currentProjectDeadline: () => {
          if (!this.data.currentProject) return null;
          
          const deadline = this.data.currentProject.PROJECT_DEADLINE;
          const now = this.data.now;
          const daysLeft = dateHelper.diff(deadline, now, 'day');
          
          return {
            formatted: dateHelper.formatDate(deadline),
            timeAgo: dateHelper.timeAgo(deadline),
            daysLeft: daysLeft > 0 ? daysLeft : 0,
            status: this._getDeadlineStatus(deadline),
            isExpired: dateHelper.isBefore(deadline, now)
          };
        },
        
        // 日历消息
        calendarText: () => {
          return dateHelper.dayjs(this.data.selectedDate).calendar();
        }
      });
      
      // 绑定计算字段
      this.setData({
        isLoading: true
      });
      
      // 加载数据
      this._loadData();
    },
    
    detached() {
      // 清理MobX绑定
      this.storeBindings.destroyStoreBindings();
      this.computedFields.dispose();
    }
  },

  methods: {
    // 加载数据
    async _loadData() {
      try {
        this.setData({ isLoading: true });
        await this.loadList();
        
        // 加载第一个项目的详情
        if (this.data.projectList.length > 0) {
          await this.loadProjectDetail(this.data.projectList[0]._id);
        }
      } catch (error) {
        wx.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
        console.error('加载数据失败', error);
      } finally {
        this.setData({ isLoading: false });
      }
    },
    
    // 更新所选日期
    updateSelectedDate(e) {
      const timestamp = e.detail.value;
      this.setData({
        selectedDate: new Date(timestamp).getTime()
      });
    },
    
    // 添加天数
    addDays(e) {
      const days = Number(e.currentTarget.dataset.days || 1);
      const newDate = dateHelper.add(this.data.selectedDate, days, 'day');
      
      this.setData({
        selectedDate: newDate.getTime()
      });
    },
    
    // 减少天数
    subtractDays(e) {
      const days = Number(e.currentTarget.dataset.days || 1);
      const newDate = dateHelper.subtract(this.data.selectedDate, days, 'day');
      
      this.setData({
        selectedDate: newDate.getTime()
      });
    },
    
    // 重置到今天
    resetToToday() {
      this.setData({
        selectedDate: this.data.now
      });
    },
    
    // 获取项目详情
    async getProjectDetail(e) {
      const projectId = e.currentTarget.dataset.id;
      if (!projectId) return;
      
      try {
        this.setData({ isLoading: true });
        await this.loadProjectDetail(projectId);
      } catch (error) {
        wx.showToast({
          title: '加载项目详情失败',
          icon: 'none'
        });
        console.error('加载项目详情失败', error);
      } finally {
        this.setData({ isLoading: false });
      }
    },
    
    // 更新计算日期属性
    _updateDateComputed(date) {
      if (!date) return;
      
      // 实际业务场景中可能需要更新其他相关数据
      console.log('日期已更新:', dateHelper.formatDate(date));
    },
    
    // 获取截止日期状态
    _getDeadlineStatus(deadline) {
      if (!deadline) return 'normal';
      
      const now = this.data.now;
      if (deadline < now) return 'expired';
      
      const daysLeft = dateHelper.diff(deadline, now, 'day');
      if (daysLeft <= 3) return 'urgent';
      if (daysLeft <= 7) return 'warning';
      return 'normal';
    }
  }
}); 